<?php
namespace Weixin\Controller;

class AuthController extends BaseController {
	/**
	 * 网页认证入口
	 */
    public function index(){
//     	$this->weObj->valid(); //微信回调地址验证
		$redirect = $this->weObj->getOauthRedirect(C('WEIXIN_CALLBACK'));
		redirect($redirect);
    }
    
    /**
     * 配置文件WEIXIN_CALLBACK对应的地址
     */
    public function next(){
    	$code = isset($_GET['code'])?$_GET['code']:'';
    	if($code){
    		$json = $this->weObj->getOauthAccessToken();
    		$_SESSION['access_token'] = $json['access_token'];
    		$user = $this->weObj->getOauthUserinfo($json['access_token'],$json['openid']);
    		if(!$user['openid']){
    			$this->error('用户信息为空，认证失败');
    			exit();
    		}
    		$Usermodel = M('Users');
    		$userinfo = $Usermodel->where(array('openid'=>$user['openid']))->find();
    		if(!$userinfo){
    			$data = array(
    					'openid' => $user['openid'],
    					'nickname' => $user['nickname'],
    					'sex' => $user['sex'],
    					'city' => $user['city'],
    					'province' => $user['province'],
    					'country' => $user['country'],
    					'headimgurl' => $user['headimgurl'],
    					'role' => 'user',
    					'type' => 'weixin',
    					'create_time' => Date('Y-m-d H:i:s'),
    					'update_time' => Date('Y-m-d H:i:s'),
    			);
    			$insertId = $Usermodel->add($data);
    			if($insertId){
    				$userinfo = $Usermodel->find($insertId);
    			}
    		}
    		if(!$userinfo['mobile']){
    			redirect('/Home/User/bangding/uid/'.$userinfo['uid']);
    			exit();
    		}
    		
    		session('_loginUser_home',$userinfo);
    		//跳转
    		if($_SESSION['_go']){
    			$url = $_SESSION['_go'];
    			session('_go',null);//删除session
    		}else{
    			$url = U('Home/my/index');
    		}
    		redirect($url);
    		
    	}else{
    		$this->error("认证失败");
    	}
    }
    
}